package shopping.filter;

import shopping.utils.JdbcUtils;

import javax.servlet.*;
import java.io.IOException;

public class TransactionFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        try {
            filterChain.doFilter(servletRequest,servletResponse);
            JdbcUtils.commitAndClose();//提交事务并释放连接
        } catch (Exception e) {
            JdbcUtils.rollbackAndClose();//回滚事务并释放连接
            e.printStackTrace();
//            throw new RuntimeException(e);//将异常抛给Tomcat服务器统一处理
        }
    }

    @Override
    public void destroy() {

    }
}
